﻿using Dapper;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.SignalR;
using MySql.Data.MySqlClient;
using System.Text;
using Warehouse.Api.Read.AGCation.Signal;
using Warehouse.Api.Read.Dtos;

namespace Warehouse.Api.Read.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class SignalRHubController : ControllerBase
    {
        public readonly IHubContext<SignalRHub> _hubContext;

        public SignalRHubController(IHubContext<SignalRHub> hubContext)
        {
            _hubContext = hubContext;
        }
        [HttpGet("push")]
        public async Task<IActionResult> Push()
        {
            try
            {
                var  sqlBuilder = new StringBuilder();
                sqlBuilder.Append(@" SELECT 
                   a.AssociatedOrderNumber,
                   a.SupplierName,
                   a.IncomingQuantity,
                   a.Totalprice,   
                   a.PreparedName,
                   a.PreparedTime,
                   b.ProductName,
                   a.Price,                     
                   c.LocationName,
                   d.AllocateWarehouseIn,       
                   d.OrderNumber                
                FROM 
              stocking a  
             JOIN ProductModel b ON a.ProductId = b.ProductId 
             JOIN LocationModel c ON a.StorageId = c.LocationId
             LEFT JOIN AllocateModel d ON a.AllocateId = d.AllocateId 
             WHERE a.IsDeleted =0 and b.IsDel =0 and c.IsDel=0 and d.IsDel=0");
                using var conn = new MySqlConnection("server=120.27.210.76;uid=wms_user;pwd=MyPassword123!;database=warehousemanagement;CharSet=utf8mb4;");
                await conn.OpenAsync();
                var data = await conn.QueryAsync<TransferDto>(sqlBuilder.ToString());
                await _hubContext.Clients.All.SendAsync("transferDto", data.ToList());
                return Ok();


            }
            catch (Exception ex)
            {
                return BadRequest(ex.Message);
            }
        }
    }
}
